package conference;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Saves a conference to a file and reads from files to
 * recreate a conference. Uses java's built in serialization.
 * 
 * @author Shawn Paul Smith - ssmith35
 */
public class ConferenceIO {
	/** The extension for filenames of saved conferences. **/
	public static final String CONF_EXTEN = ".ezc";

	/**
	 * Serializes a conferences and saves it in the given
	 * path. Returns if save worked.
	 **/
	public static boolean saveConference(String path,
			Conference confToSave) {
		boolean results;
		String confFolderPath = path + File.separator
				+ confToSave.getConfName();
		// Opens the folder to save the conference in
		// creating it if it doesn't exist.
		File confFolder = new File(confFolderPath);
		if (!confFolder.exists()) {
			confFolder.mkdir();
			System.out.println("Created conferance folder");
		}
		try {
			FileOutputStream fileOut = new FileOutputStream(
					confFolderPath + File.separator
							+ confToSave.getConfName()
							+ CONF_EXTEN);
			ObjectOutputStream confOut =
					new ObjectOutputStream(fileOut);
			confOut.writeObject(confToSave);
			confOut.close();
			results = true;
		} catch (IOException e) {
			System.out.println(e.getMessage());
			results = false;
		}
		return results;
	}

	/**
	 * Attempts to deserialize a previously saved
	 * conference, returning the Conference if it exists,
	 * or null if not.
	 */
	public static Conference loadConference(String path,
			String confName) {
		// the full path and filename of the expected file.
		String confFileName = path + File.separator
				+ confName + File.separator + confName
				+ CONF_EXTEN;
		File confFile = new File(confFileName);
		Conference results = null;
		try {
			FileInputStream fileIn = new FileInputStream(
					confFile);
			ObjectInputStream objIn = new ObjectInputStream(
					fileIn);
			Object obj = objIn.readObject();
			if (obj instanceof Conference) {
				results = (Conference) obj;
			}
		} catch (IOException e) {
			System.out.println("Creating new conference");
		} catch (ClassNotFoundException e) {
			System.err.println("Unable to deserialize");
		}
		return results;
	}
}
